import React, { Component } from "react";
import { debounce } from "../../utils";
import './index.css';
export default class VirtualList extends Component<VirtualListProps> {
  state = {
    start: 0, //起始索引值
  };
  handleToScroll(itemHeight: any, nextkeyWordsLine: any) {
    this.scrollBox&&this.scrollBox.scrollTo({
      top: itemHeight * nextkeyWordsLine,
      left: 0,
      behavior: "smooth"
    })
  }
  scrollBox:any=null;
  handleScroll = () => {
    let { options: { itemHeight, bothAppend, dom } } = this.props;
    const { scrollTop }: any = dom ? dom.current : this.scrollBox;
    const start = Math.floor(scrollTop / itemHeight) - (bothAppend || 0); //向下取整，尽可能往小里算，这样的话可以显示上面一般被滑动出去的内容。
    this.setState({ start });
  };
  render() {
    let {
      options: {
        width,
        height,
        count,
        itemHeight,
        renderItem,
        itemWidth,
        loading,
        appendNum,
        delay,
        bothAppend,
        dom
      },
    } = this.props;

    let windowHeight = window.innerHeight;
    height =
      typeof height === "string"
        ? windowHeight * (parseInt(height) / 100)
        : height;
    /**
     * 注意：页面里面的div是有最大高度限制的，在本人机器上测试为三千五百万px为极限，此时将可能出现不展示后续内容的问题。
     */
    const { start } = this.state; //中间区域的开始值

    let end = start + Math.ceil(height / itemHeight) + (appendNum || 0) + (bothAppend ? bothAppend * 2 : 0); //中间区域的结束值，尽可能多一个，向上取整。
    end = end > count ? count : end; //防止结束的索引越界，超过最后一条
    const variableList = new Array(end - start)
      .fill(0)
      .map((item, index) => ({ index: start + index })); //需要渲染的条目

    let itemStyle = {
      position: "absolute",
      left: 0,
      width: itemWidth,
      height: itemHeight,
    };
    return (
      <div
        className="virtualList-container"
        style={{
          height,
          width,
        }}
        ref={(element) => { 
          this.scrollBox = element;
          dom.current = element 
        }}
        // onScroll={debounce(this.handleScroll,1000)}
        onScroll={debounce(this.handleScroll, delay)}
      >
        <div
          className="virtualList-container-inner"
          style={{
            height: `${count * itemHeight}px`,
          }}
        >
          {variableList.map(({ index }) =>
            renderItem({
              index,
              style: {
                ...itemStyle,
                top: itemHeight * index,
                //marginTop: itemHeight * index,
              },
            })
          )}
          <div
            className="virtualList-loading"
            style={{
              top: itemHeight * end,
            }}
          >
            {loading && loading}
          </div>
        </div>
      </div>
    );
  }
}
